<template>
  <div class="edit-article">
    <!-- 第一行 -->
    <span class="edit-thead">
      <div>{{ isEdit ? '编辑' : '发布' }}文章</div>
      <div><van-icon name="cross" /></div>
    </span>
    <!-- 除了第一行的其他行 -->
    <div class="bottom">
      <!-- 1.文章标题 -->
      <div class="art-title">
        <span>文章标题</span>
        <el-input style="width: 240px" placeholder="请输入标题"  v-model="publishData.title"></el-input>
      </div>
      <!-- 2.文章分类 -->
      <div class="art-cate">
        <span>文章分类</span>
        <el-select placeholder="请选择" style="width: 240px" v-model="publishData.category">
          <el-option label="学习" :value="0"></el-option>
          <el-option label="生活" :value="1"></el-option>
          <el-option label="社交" :value="2"></el-option>
          <el-option label="职业" :value="3"></el-option>
        </el-select>

      </div>

      <!-- 3.文章封面 -->
      <div class="img">
        <span>文章封面</span>
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleChange"
        >
          <img v-if="publishData.images" :src="publishData.images" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
              <path fill="currentColor" d="M480 480V128a32 32 0 0 1 64 0v352h352a32 32 0 1 1 0 64H544v352a32 32 0 1 1-64 0V544H128a32 32 0 0 1 0-64z"></path>
            </svg>
          </el-icon>
        </el-upload>
      </div>
      <!-- 4.文章内容 -->
      <div class="content">
        <span class="art-tent">文章内容</span>
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          >
          </Toolbar>
          <Editor
            style="height: 300px; overflow-y: hidden;"
            v-model="publishData.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          >
          </Editor>
        </div>
      </div>
      <!-- 按钮 -->
      <div class="button">
        <el-button type="primary" @click="clickHandler">{{ isEdit ? '编辑' : '发布' }}</el-button>
        <el-button type="danger" @click="goBackToHome">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script setup >
// 编辑器
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {publishAPI, updatePostAPI} from '@/api/publish.js'
import {  useRouter, useRoute } from 'vue-router';
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { defineOptions } from 'vue';
import {ElMessage} from 'element-plus'
import {getPostInfoAPI, postPicAPI} from '@/api/post';
import {useUserStore} from "@/stores/userStore.js";

defineOptions({
  name: 'EditComponent' // 多单词命名，消除警告
});

const userStore = useUserStore()
const publishData=ref({
  content:'',
  title:'',
  userId: +userStore.userInfo.userId,
  images:'',
  comments: 0,
  category: 0
})

// 编辑器实例
const editorRef = shallowRef()
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }
const mode = 'default'
// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (!editor) return
  editor.destroy()
})
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 将富文本转为纯文本
function htmlToPlainText(html) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  return doc.body.textContent.trim();
}

// 获取路由实例
const router = useRouter()
const clickHandler = async ()=>{
  // 非空判断
  if (!publishData.value.title) return ElMessage.warning('文章标题不能为空')
  if (!htmlToPlainText(publishData.value.content)) return ElMessage.warning('文章内容不能为空')

  try {
    if (isEdit.value) {
      // 编辑场景
      const res = await updatePostAPI(publishData.value)
      if (res.code === 200) {
        ElMessage.success('编辑成功')
      }
    } else {
      // 发布场景
      const res = await publishAPI(publishData.value)
      if (res.code === 200) {
        ElMessage.success('发布成功')
      }
    }
    router.push('/home')
  } catch (e) {
    ElMessage.error('错误操作')
  }
}

// 返回首页
const goBackToHome = () => {
  router.push('/home');
};

const handleChange = async (file) => {
  const selectedFile = file.raw; // 获取原始文件对象

  const formData = new FormData();
  formData.append('file', selectedFile); // 'file' 是服务器接收文件的字段名，需根据实际情况修改

  const res = await postPicAPI(formData)
  publishData.value.images = res.data
}

// 获取路径上的id
const route = useRoute()
const isEdit = ref(false) // 是否是编辑场景
onMounted(async () => {
  const id = route.query.id
  if (!id) return // 判断是否有 id，有就是编辑场景，没有就是发布场景
  isEdit.value = true // 设置为编辑场景

  // 获取数据
  try {
    const res = await getPostInfoAPI(id)
    if (res.code === 200) {
      publishData.value.title = res.data.title
      publishData.value.category = res.data.category
      publishData.value.images = res.data.images
      publishData.value.content = res.data.content
      publishData.value.id = +res.data.id
    }
  } catch (err) {
    ElMessage.error('获取帖子信息错误')
  }
})
</script>

<style scoped>
/* 整体样式 */
body {
  font-family: Arial, sans-serif;
  font-size: 16px;
  margin: 0;
  padding: 0;
}

/* 主体 */
.edit-article {
  padding: 20px;
}

.edit-thead{
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 700;
  height: 40px;
  line-height: 40px;
  width: 80%;
  margin: 0 auto;
}

/* 下面整个即除了thead */
.bottom{
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 80%;
  margin: 0 auto;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  padding: 20px;
  border-radius: 5px;
}

.art-title {
  margin-bottom: 10px;
}

/* 编辑器 */
.content{
  margin-top: 20px;
}

/* 文章封面 */
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
  border-radius: 5px;
}

.img{
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.img span{
  margin-right: 10px;
}

/* 文章内容 */
.content{
  margin-top: 20px;
}

.content .art-tent{
  margin-right: 10px;
  width: 100%;
  line-height: 30px;
}

/* 文章标题 */
.art-title span,.art-cate span{
  margin-right: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
  line-height: 150px;
}

/* 按钮 */
.button{
  margin-top: 20px;
  display: flex;
  gap: 10px;
}
</style>
